package cn.yuanqiao.system.service.impl;

import cn.yuanqiao.archive.appManager.domain.TenantSysConfig;
import cn.yuanqiao.archive.appManager.mapper.TenantSysConfigMapper;
import cn.yuanqiao.common.annotation.DataScope;
import cn.yuanqiao.common.constant.SysContants;
import cn.yuanqiao.common.constant.UserConstants;
import cn.yuanqiao.common.core.domain.R;
import cn.yuanqiao.common.core.domain.TreeSelect;
import cn.yuanqiao.common.core.domain.entity.SysDept;
import cn.yuanqiao.common.core.domain.entity.SysRole;
import cn.yuanqiao.common.core.domain.entity.SysUser;
import cn.yuanqiao.common.core.domain.model.LoginUser;
import cn.yuanqiao.common.exception.ServiceException;
import cn.yuanqiao.common.service.SysPermissionService;
import cn.yuanqiao.common.utils.SecurityUtils;
import cn.yuanqiao.common.utils.SnowflakeIdGenerator;
import cn.yuanqiao.common.utils.StringUtils;
import cn.yuanqiao.common.utils.bean.BeanValidators;
import cn.yuanqiao.common.utils.spring.SpringUtils;
import cn.yuanqiao.system.domain.SysPost;
import cn.yuanqiao.system.domain.SysUserPost;
import cn.yuanqiao.system.domain.SysUserRole;
import cn.yuanqiao.system.mapper.*;
import cn.yuanqiao.system.service.ISysConfigService;
import cn.yuanqiao.system.service.ISysRoleService;
import cn.yuanqiao.system.service.ISysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;

import javax.validation.Validator;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 用户 业务层处理
 *
 * @author ruoyi
 */
@Service
public class SysUserServiceImpl implements ISysUserService {
    private static final Logger log = LoggerFactory.getLogger(SysUserServiceImpl.class);

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private SysRoleMapper roleMapper;

    @Autowired
    private SysPostMapper postMapper;

    @Autowired
    private SysUserRoleMapper userRoleMapper;

    @Autowired
    private SysUserPostMapper userPostMapper;

    @Autowired
    private SysRoleMenuMapper sysRoleMenuMapper;

    @Autowired
    private SysMenuMapper sysMenuMapper;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    protected Validator validator;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private ISysRoleService roleService;

    @Value("${FBswitch}")
    private boolean FBswitch;
    @Value("${encryption}")
    private String encryption;
    @Autowired
    private SysDeptMapper sysDeptMapper;
    @Autowired
    private SysRoleMapper sysRoleMapper;
    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;
    @Autowired
    private TenantSysConfigMapper tenantSysConfigMapper;

    /**
     * 根据条件分页查询用户列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<SysUser> selectUserList(SysUser user) {
        //String tenantCode = SecurityUtils.getTenantCode();
        user.setTenantCode(SecurityUtils.getTenantCode());
        return userMapper.selectUserList(user);
    }

    @Override
    //@DataScope(deptAlias = "d", userAlias = "u")
    public List<SysUser> selectSysList(SysUser user) {
        return userMapper.selectSysList(user);
    }

    /**
     * 根据条件分页查询已分配用户角色列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<SysUser> selectAllocatedList(SysUser user) {
        return userMapper.selectAllocatedList(user);
    }

    /**
     * 根据条件分页查询未分配用户角色列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<SysUser> selectUnallocatedList(SysUser user) {
        return userMapper.selectUnallocatedList(user);
    }


    /**
     * 通过用户名查询用户
     *
     * @param userName 用户名
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserByUserName(String userName, String tenantCode) {
        if ("admin".equals(userName)) {
            return userMapper.selectUserByUserNameOfAdmin(userName);
        } else {
            return userMapper.selectUserByUserName(userName, tenantCode);
        }
    }

    @Override
    public List<Long> selectUserByTenantCode(String tenantCode) {
        return userMapper.selectUserByTenantCode(tenantCode);

    }

    /**
     * 通过用户ID查询用户
     *
     * @param userId 用户ID
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserById(Long userId) {
        return userMapper.selectUserById(userId);
    }

    @Override
    public SysUser selectUserByRemark(String remark) {
        return userMapper.selectUserByRemark(remark);
    }

    /**
     * 查询用户所属角色组
     *
     * @param userName 用户名
     * @return 结果
     */
    @Override
    public String selectUserRoleGroupTenantCode(String userName, String tenantCode) {
        List<SysRole> list = roleMapper.selectRolesByUserNameTenantCode(userName, tenantCode);

        if (CollectionUtils.isEmpty(list)) {
            return StringUtils.EMPTY;
        }
        return list.stream().map(SysRole::getRoleName).collect(Collectors.joining(","));
    }

    /**
     * 查询用户所属角色组
     *
     * @param userName 用户名
     * @return 结果
     */
    @Override
    public String selectUserRoleGroup(String userName) {
        List<SysRole> list = roleMapper.selectRolesByUserName(userName);
        if (CollectionUtils.isEmpty(list)) {
            return StringUtils.EMPTY;
        }
        return list.stream().map(SysRole::getRoleName).collect(Collectors.joining(","));
    }


    /**
     * 查询用户所属岗位组
     *
     * @param userName 用户名
     * @return 结果
     */
    @Override
    public String selectUserPostGroup(String userName) {
        List<SysPost> list = postMapper.selectPostsByUserName(userName);
        if (CollectionUtils.isEmpty(list)) {
            return StringUtils.EMPTY;
        }
        return list.stream().map(SysPost::getPostName).collect(Collectors.joining(","));
    }

    /**
     * 校验登录名称是否唯一
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public boolean checkUserNameUnique(SysUser user) {
        String tenantCode = SecurityUtils.getTenantCode();
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = userMapper.checkUserNameUnique(user.getUserName(), tenantCode);
        if (StringUtils.isNotNull(info)&& info.getUserId() != userId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验手机号码是否唯一
     *
     * @param user 用户信息
     * @return
     */
    @Override
    public boolean checkPhoneUnique(SysUser user) {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = userMapper.checkPhoneUnique(user.getPhonenumber());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验email是否唯一
     *
     * @param user 用户信息
     * @return
     */
    @Override
    public boolean checkEmailUnique(SysUser user) {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = userMapper.checkEmailUnique(user.getEmail());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验用户是否允许操作
     *
     * @param user 用户信息
     */
    @Override
    public void checkUserAllowed(SysUser user) {
        if (StringUtils.isNotNull(user.getUserId()) && user.isAdmin()) {
            throw new ServiceException("不允许操作超级管理员用户");
        }
    }

    /**
     * 校验用户是否有数据权限
     *
     * @param userId 用户id
     */
    @Override
    public void checkUserDataScope(Long userId) {
        if (!SysUser.isAdmin(SecurityUtils.getUserId()) && !SecurityUtils.isSanYuan()) {
            SysUser user = new SysUser();
            user.setUserId(userId);
            List<SysUser> users = SpringUtils.getAopProxy(this).selectUserList(user);
            //   ---xy
            if (StringUtils.isEmpty(users)) {
                throw new ServiceException("没有权限访问用户数据！");
            }
        }
    }

    /**
     * 新增保存用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertUser(SysUser user) {
        // 新增用户信息
        String tenantCode = SecurityUtils.getTenantCode();
        if (null != tenantCode && StringUtils.isNotEmpty(tenantCode) && !"null".equals(tenantCode)) {
            user.setTenantCode(tenantCode);
        }
        int rows = userMapper.insertUser(user);
        // 新增用户岗位关联
        insertUserPost(user);
        // 新增用户与角色管理
        insertUserRole(user);
        return rows;
    }

    /**
     * 注册用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public boolean registerUser(SysUser user) {
        return userMapper.insertUser(user) > 0;
    }

    /**
     * 修改保存用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateUser(SysUser user) {
        Long userId = user.getUserId();
        String password = user.getPassword();
        if (StringUtils.isNotEmpty(password) && !"null".equals(password) && !SecurityUtils.isBcrypt(password)) {
            user.setPassword(SecurityUtils.encryptPassword(user.getPassword(), encryption));
        }
        // 删除用户与角色关联
        userRoleMapper.deleteUserRoleByUserId(userId);
        // 新增用户与角色管理
        insertUserRole(user);
        // 删除用户与岗位关联
        userPostMapper.deleteUserPostByUserId(userId);
        // 新增用户与岗位管理
        insertUserPost(user);
        return userMapper.updateUser(user);
    }
    /*@Override
    public int editSys(SysUser user)
    {
        String pwd = userMapper.getPwdById(user.getUserId());
        String password = user.getPassword();
        if(StringUtils.isNotEmpty(password) && !"null".equals(password)){
            if(!pwd.equals(password)){
                user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
            }
        }
        return userMapper.editSys(user);
    }*/

    /**
     * 用户授权角色
     *
     * @param userId  用户ID
     * @param roleIds 角色组
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void insertUserAuth(Long userId, Long[] roleIds) {
        userRoleMapper.deleteUserRoleByUserId(userId);
        insertUserRole(userId, roleIds);
    }

    /**
     * 修改用户状态
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int updateUserStatus(SysUser user) {
        return userMapper.updateUser(user);
    }

    /**
     * 修改用户基本信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int updateUserProfile(SysUser user) {
        return userMapper.updateUser(user);
    }

    /**
     * 修改用户头像
     *
     * @param userName 用户名
     * @param avatar   头像地址
     * @return 结果
     */
    @Override
    public boolean updateUserAvatar(String userName, String avatar) {
        String userType = SecurityUtils.getUserType();
        if (SysContants.MANAGEDEPTFLAG.equals(userType)) {
            return userMapper.updateManageAvatar(userName, avatar) > 0;
        }
        return userMapper.updateUserAvatar(userName, avatar, SecurityUtils.getTenantCode()) > 0;
    }

    /**
     * 重置用户密码
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int resetPwd(SysUser user) {
        return userMapper.updateUser(user);
    }

    @Override
    public String editSys(SysUser user) {
        String pwd = userMapper.getPwdById(user.getUserId());
        String password = user.getPassword();
        if (StringUtils.isNotEmpty(password) && !"null".equals(password)) {
            if (!pwd.equals(password)) {
                user.setPassword(SecurityUtils.encryptPassword(user.getPassword(), encryption));
            }
        }
        if (FBswitch) {
            SysUser sysUser = userMapper.selectUserById(user.getUserId());
            if (!"sysadmin".equals(sysUser.getUserName()) && !"syssso".equals(sysUser.getUserName()) && !"sysauditor".equals(sysUser.getUserName())) {
                if (null == user.getMiJi() || "".equals(user.getMiJi())) {
                    return "人员密级不能为空";
                }
            }
        }
        int i = userMapper.editSys(user);
        if (i > 0) {
            return "success";
        } else {
            return "fail";
        }
    }

    /**
     * 重置用户密码
     *
     * @param userName 用户名
     * @param password 密码
     * @return 结果
     */
    @Override
    public int resetUserPwd(String userName, String password) {
        return userMapper.resetUserPwd(userName, password, SecurityUtils.getTenantCode());
    }

    /**
     * 新增用户角色信息
     *
     * @param user 用户对象
     */
    public void insertUserRole(SysUser user) {
        this.insertUserRole(user.getUserId(), user.getRoleIds());
    }

    /**
     * 新增用户岗位信息
     *
     * @param user 用户对象
     */
    public void insertUserPost(SysUser user) {
        Long[] posts = user.getPostIds();
        if (StringUtils.isNotEmpty(posts)) {
            // 新增用户与岗位管理
            List<SysUserPost> list = new ArrayList<SysUserPost>();
            for (Long postId : posts) {
                SysUserPost up = new SysUserPost();
                up.setUserId(user.getUserId());
                up.setPostId(postId);
                list.add(up);
            }
            userPostMapper.batchUserPost(list);
        }
    }

    /**
     * 新增用户角色信息
     *
     * @param userId  用户ID
     * @param roleIds 角色组
     */
    public void insertUserRole(Long userId, Long[] roleIds) {
        if (StringUtils.isNotEmpty(roleIds)) {
            // 新增用户与角色管理
            List<SysUserRole> list = new ArrayList<SysUserRole>();
            for (Long roleId : roleIds) {
                SysUserRole ur = new SysUserRole();
                ur.setUserId(userId);
                ur.setRoleId(roleId);
                list.add(ur);
            }
            userRoleMapper.batchUserRole(list);
        }
    }

    /**
     * 通过用户ID删除用户
     *
     * @param userId 用户ID
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteUserById(Long userId) {
        // 删除用户与角色关联
        userRoleMapper.deleteUserRoleByUserId(userId);
        // 删除用户与岗位表
        userPostMapper.deleteUserPostByUserId(userId);
        return userMapper.deleteUserById(userId);
    }

    /**
     * 批量删除用户信息
     *
     * @param userIds 需要删除的用户ID
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteUserByIds(Long[] userIds) {
        for (Long userId : userIds) {
            checkUserAllowed(new SysUser(userId));
            checkUserDataScope(userId);
        }
        // 删除用户与角色关联
        userRoleMapper.deleteUserRole(userIds);
        // 删除用户与岗位关联
        userPostMapper.deleteUserPost(userIds);
        return userMapper.deleteUserByIds(userIds);
    }

    /**
     * 导入用户数据
     *
     * @param userList        用户数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName        操作用户
     * @return 结果
     */
    @Override
    public String importUser(List<SysUser> userList, Boolean isUpdateSupport, String operName, Long deptId) {
        if (StringUtils.isNull(userList) || userList.size() == 0) {
            throw new ServiceException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        String password = configService.selectConfigByKey("sys.user.initPassword");
        for (SysUser user : userList) {
            try {
                if(user == null){
                    throw new ServiceException("格式数据错误!");
                }
                // 验证是否存在这个用户
                String tenantCode = SecurityUtils.getTenantCode();
                SysUser u = userMapper.selectUserByUserName(user.getUserName(), tenantCode);
                if (StringUtils.isNull(u)) {
                    BeanValidators.validateWithException(validator, user);
                    user.setPassword(SecurityUtils.encryptPassword(password, encryption));
                    user.setCreateBy(operName);
                    user.setTenantCode(tenantCode);
                    user.setDeptId(deptId);
                    userMapper.insertUser(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 导入成功");
                } else if (isUpdateSupport) {
                    BeanValidators.validateWithException(validator, user);
                    checkUserAllowed(u);
                    checkUserDataScope(u.getUserId());
                    user.setUserId(u.getUserId());
                    user.setUpdateBy(operName);
                    user.setTenantCode(tenantCode);
                    user.setDeptId(deptId);
                    userMapper.updateUser(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 更新成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、账号 " + user.getUserName() + " 已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "";
                if(user !=null && user.getUserName()!=null){
                    msg = "<br/>" + failureNum + "、账号 " + user.getUserName() + " 导入失败：";
                }else {
                    msg = "<br/>" + failureNum + "导入失败;";
                }
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    @Override
    public String selectUserPostGroupTenantCode(String username, String tenantCode) {
        List<SysPost> list = postMapper.selectPostsByUserNameTenantCode(username, tenantCode);
        if (CollectionUtils.isEmpty(list)) {
            return StringUtils.EMPTY;
        }
        return list.stream().map(SysPost::getPostName).collect(Collectors.joining(","));
    }

    @Override
    public List<List<String>> exporttongjith() {
        List<List<String>> strlist = new ArrayList<List<String>>() {{
            List<String> list1 = new ArrayList<String>() {{
                add("序号");
            }};
            add(list1);
            List<String> list2 = new ArrayList<String>() {{
                add("登录账号");
            }};
            add(list2);
            List<String> list3 = new ArrayList<String>() {{
                add("用户昵称");
            }};
            add(list3);
            List<String> list4 = new ArrayList<String>() {{
                add("用户邮箱");
            }};
            add(list4);
            List<String> list5 = new ArrayList<String>() {{
                add("手机号码");
            }};
            add(list5);
            List<String> list6 = new ArrayList<String>() {{
                add("用户性别");
            }};
            add(list6);
            List<String> list7 = new ArrayList<String>() {{
                add("帐号状态(正常,停用)");
            }};
            add(list7);
        }};
        return strlist;
    }

    @Override
    public List<SysUser> synchronizationUserList(SysUser sysUser) {
        return userMapper.synchronizationUserList(sysUser);

    }

    @Override
    public List<SysUser> selectSysUserByRoleKeyAndDeptId(String roleKey, String deptId, String tenantCode) {
        return userMapper.selectSysUserByRoleKeyAndDeptId(roleKey, deptId, tenantCode);
    }

    @Override
    public List<SysUser> selectSysUserByRoleKey(String roleKey, String tenantCode) {
        return userMapper.selectSysUserByRoleKey(roleKey, tenantCode);
    }

    @Override
    public List<TreeSelect> roleUserTreeNoDateScope(SysRole role) {
        SysRole roleSelect = roleMapper.selectRoleByRoleKeyAndTenantCode(role);
        List<SysUser> sysUsers = userMapper.selectSysUserByRoleKey(role.getRoleKey(), SecurityUtils.getTenantCode());
        List<TreeSelect> collect = sysUsers.stream().map(TreeSelect::new).collect(Collectors.toList());
        TreeSelect treeSelect = new TreeSelect();
        treeSelect.setId(roleSelect.getRoleId());
        treeSelect.setLabel(roleSelect.getRoleName());
        treeSelect.setUserChildren(collect);
        List<TreeSelect> list = new ArrayList<>();
        list.add(treeSelect);
        return list;
    }

    @Override
    public LoginUser getUserInfo(String username, String tenantCode) {
        SysUser sysUser = selectUserByUserName(username, tenantCode);
        if (StringUtils.isNull(sysUser)) {
            return null;
        }
        // 角色集合
        List<SysRole> sysRoles = roleMapper.selectRolePermissionByUserId(sysUser.getUserId());
        //Set<String> roles = permissionService.getRolePermission(sysUser);
        // 权限集合
        Set<String> permissions = new HashSet<String>();
        // 管理员拥有所有权限
        if (sysUser.isAdmin()) {
            permissions.add("*:*:*");
        } else {
            List<SysRole> roles = sysUser.getRoles();
            if (!roles.isEmpty() && roles.size() > 1) {
                // 多角色设置permissions属性，以便数据权限匹配权限
                for (SysRole role : roles) {
                    //Set<String> rolePerms = menuService.selectMenuPermsByRoleId(role.getRoleId());
                    List<String> perms = sysMenuMapper.selectMenuPermsByRoleId(role.getRoleId());
                    Set<String> rolePerms = new HashSet<>();
                    for (String perm : perms) {
                        if (StringUtils.isNotEmpty(perm)) {
                            rolePerms.addAll(Arrays.asList(perm.trim().split(",")));
                        }
                    }
                    role.setPermissions(rolePerms);
                    permissions.addAll(rolePerms);
                }
            } else {
                permissions.addAll(sysMenuMapper.selectMenuPermsByUserId(sysUser.getUserId()));
            }
        }
        Map<Long, List<Long>> menuIdsOfRoles = new HashMap<>();
        List<SysRole> userRoles = roleMapper.selectRolePermissionByUserId(sysUser.getUserId());
        if (userRoles != null && userRoles.size() != 0) {
            userRoles.stream().forEach(k -> {
                Long roleId = k.getRoleId();
                List<Long> menuIds = sysRoleMenuMapper.selectMenuIdsByRoleId(roleId);
                menuIdsOfRoles.put(roleId, menuIds);
            });
        }
        sysUser.setMenuIdsOfRoles(menuIdsOfRoles);
        LoginUser sysUserVo = new LoginUser();
        sysUserVo.setUser(sysUser);
        sysUserVo.setRoles(sysRoles.stream().map(SysRole::getRoleKey).collect(Collectors.toSet()));
        sysUserVo.setPermissions(permissions);
        return sysUserVo;
    }

    @Override
    public R<LoginUser> getUserInfo(String username,String tenantcode, String source)
    {
        SysUser sysUser = userService.selectUserByUserName(username, tenantcode);
        if (StringUtils.isNull(sysUser)) {
            return R.fail("用户名或密码错误");
        }
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(sysUser);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(sysUser);
        Map<Long, List<Long>> menuIdsOfRoles = roleService.selectMenuIdsByRoleId(sysUser.getUserId());
        sysUser.setMenuIdsOfRoles(menuIdsOfRoles);
        LoginUser sysUserVo = new LoginUser();
        sysUserVo.setUser(sysUser);
        sysUserVo.setRoles(roles);
        sysUserVo.setPermissions(permissions);
        return R.ok(sysUserVo);
    }

    @Override
    public R changeStatusApi(@RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        user.setUpdateBy(SecurityUtils.getUsername());
        return R.ok(userService.updateUserStatus(user));
    }

    @Override
    public R<SysUser> addAsync(SysUser sysUser) {
        if (!checkUserNameUnique(sysUser)) {
            return R.fail("新增用户'" + sysUser.getUserName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(sysUser.getPhonenumber()) && !checkPhoneUnique(sysUser)) {
            return R.fail("新增用户'" + sysUser.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(sysUser.getEmail()) && !checkEmailUnique(sysUser)) {
            return R.fail("新增用户'" + sysUser.getUserName() + "'失败，邮箱账号已存在");
        }
        insertUser(sysUser);
        return R.ok(sysUser);
    }

    @Override
    public R<Integer> editAsync(SysUser sysUser) {
        if (!checkUserNameUnique(sysUser)) {
            return R.fail("修改用户'" + sysUser.getUserName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(sysUser.getPhonenumber()) && !checkPhoneUnique(sysUser)) {
            return R.fail("修改用户'" + sysUser.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(sysUser.getEmail()) && !checkEmailUnique(sysUser)) {
            return R.fail("修改用户'" + sysUser.getUserName() + "'失败，邮箱账号已存在");
        }
        return R.ok(updateUser(sysUser));
    }

    @Override
    public R<Integer> removeAsync(Long userId) {
        return R.ok(deleteUserById(userId));
    }

    public List<String> selectUserNameByPostCodeAndDeptId(String postCode, Long deptId) {
        return userMapper.selectUserNameByPostCodeAndDeptId(postCode, deptId);
    }


    /**
     * 通过用户名查询用户
     *
     * @param userName 用户名
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserByUserName(String userName) {
        return userMapper.selectUserByUserName(userName, SecurityUtils.getLoginUser().getUser().getTenantCode());
    }

    @Override
    public List<SysUser> selectUserByUserNameAndTenantCode(String userName, String tenantCode) {
        return userMapper.selectUserByUserNameAndTenantCode(userName, tenantCode);
    }

    @Override
    public List<Map<String, Object>> selectRoleKeyByTenantCode(String tenantCode) {
        return userMapper.selectRoleKeyByTenantCode(tenantCode);
    }

    @Override
    public List<SysUser> selectUserByRoleKey(String s) {
        return userMapper.selectUserByRoleKey(s, SecurityUtils.getLoginUser().getUser().getTenantCode());
    }

    @Override
    public SysUser infoByOId(String oId) {
        return userMapper.selectUserByOId(oId);
    }


    public Integer syncUserByOA(String tenantCode){
        List<SysUser> oaUsers = userMapper.selectUserListByOther(new SysUser());
        List<SysUser> sysUsers = userMapper.selectUserList(new SysUser());
        Map<String, SysUser> sysUsersMap = sysUsers.stream()
                .filter(user -> user.getOneId() != null)  // 过滤掉 oneId 为 null 的元素
                .collect(Collectors.toMap(SysUser::getOneId, Function.identity()));

        //对比两个list集合，将sysUsers1中不存在但是susUsers中存在的数据进行更新，以oneId为唯一对比字段
        // 遍历 sysUsers，检查 sysUsers1 中是否存在相同的 oneId
        List<SysUserRole> userRoleList = new ArrayList<>();
        TenantSysConfig query = new TenantSysConfig();
        query.setTenantCode(tenantCode);
        query.setConfigKey("NNOA_USER_KEY");
        TenantSysConfig tenantSysConfig = tenantSysConfigMapper.selectConfig(query);
        Long roleId = null;
        if (tenantSysConfig != null && tenantSysConfig.getConfigValue()!=null){
            SysRole sysRole = sysRoleMapper.selectRoleByRoleKey(tenantSysConfig.getConfigValue());
            if (sysRole!=null){
                roleId = sysRole.getRoleId();
            }
        }

        for (SysUser oaUser : oaUsers) {
            SysUser sysUser = sysUsersMap.get(oaUser.getOneId());
            oaUser.setNickName(oaUser.getUserName());
            oaUser.setUserName(String.valueOf(oaUser.getOneId()));
            if (sysUser == null) {
                // 如果 sysUsersMap 中不存在相同的 oneId，则进行插入
                oaUser.setTenantCode(tenantCode);
                oaUser.setUserId(SnowflakeIdGenerator.generateId());
                SysDept sysDept = sysDeptMapper.selectDeptByOneId(oaUser.getOneDeptId());
                if (sysDept != null) {
                    oaUser.setDeptId(sysDept.getDeptId());
                    oaUser.setDept(sysDept);
                }else {
                    oaUser.setDeptId(100L);
                }
                userMapper.insertUser(oaUser);
                if (roleId != null){
                    SysUserRole sysUserRole = new SysUserRole();
                    sysUserRole.setRoleId(roleId);
                    sysUserRole.setUserId(oaUser.getUserId());
                    userRoleList.add(sysUserRole);
                }
            } else {
                // 如果 sysUsersMap 中存在相同的 oneId，则更新 sysUsers 中的数据
                oaUser.setTenantCode(tenantCode);
                oaUser.setDeptId(sysUser.getDeptId());
                userMapper.updateUserByOneId(oaUser);
            }
        }
        if (!userRoleList.isEmpty()){
            sysUserRoleMapper.batchUserRole(userRoleList);
        }
        return 0;
    }

    @Override
    public List<Long> getdaglyuser(String tenantCode) {
        return userMapper.getdaglyuser(tenantCode);
    }
}
